<!-- 工具管理-工具借出/归还页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" inline label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="工具借用单号">
              <px-input
                v-model="queryParams.toolBorrowCode"
                clearable
                placeholder="请输入工具借用单号"
                maxlength="50"
                @blur="queryParams.toolBorrowCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="工具编码">
              <px-input
                v-model="queryParams.toolCode"
                placeholder="请输入工具编码"
                maxlength="50"
                clearable
                @blur="queryParams.toolCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <!-- <EquipClassSelect customLabel="工具科室" :className="queryParams.className" @changeClassName="changeClassName" /> -->
            <px-form-item label="工具科室">
              <px-select v-model="queryParams.toolClassName" placeholder="请选择工具科室">
                <px-option v-for="item in classNameList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="借用人">
              <px-select-v2 v-model="queryParams.toolBorrower" filterable clearable :options="custodianList" placeholder="请选择借用人" />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="借用时间">
              <px-date-picker v-model="queryParams.toolBorrowDate" value-format="YYYY-MM-DD HH:mm:ss" type="datetime" placeholder="借用时间" />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="归还状态">
              <px-select v-model="queryParams.revertStatus" placeholder="请选择归还状态" filterable clearable>
                <px-option v-for="item in reverseStatusList" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="厂区">
              <px-select v-model="queryParams.factoryAreaCode" placeholder="请选择厂区">
                <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LOANRETURN_ADD'" type="primary" style="margin-right: 8px" @click="addToolsBorrow">
          新建借用单
        </px-button>
        <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LOANRETURN_BATCH_RETURN'" type="primary" plain :disabled="selectIds.length == 0" @click="batchReturn">
          批量归还
        </px-button>
      </div>
      <px-table :data="tableData" class="equip-table" height="calc(100vh - 343px)" border @selection-change="selectionChange">
        <px-table-column type="selection" :selectable="handleCanSelect" min-width="40" align="center" />
        <!-- <px-table-column fixed="left" type="index" width="50" label="序号" /> -->
        <px-table-column fixed="left" prop="toolBorrowCode" label="工具借用单号" min-width="190" show-overflow-tooltip>
          <template #default="scope">
            <span
              v-if="isHasPermission('ALL_EQUIP_TOOLMANAGE_LOANRETURN_VIEW')"
              style="color: #3b82f6; cursor: pointer"
              @click="handleView(scope.row)"
            >
              {{ scope.row.toolBorrowCode }}
            </span>
            <span v-else>{{ scope.row.toolBorrowCode }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="factoryAreaDesc" label="借用单厂区" min-width="100" show-overflow-tooltip />
        <px-table-column fixed="left" prop="toolBorrowCode" label="工具编码" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <span
              v-if="isHasPermission('ALL_EQUIP_TOOLMANAGE_LEDGER_VIEW')"
              style="color: #3b82f6; cursor: pointer"
              @click="handleViewTool(scope.row)"
            >
              {{ scope.row.toolCode }}
            </span>
            <span v-else>{{ scope.row.toolCode }}</span>
          </template>
        </px-table-column>
        <px-table-column prop="toolName" label="工具名称" min-width="120" show-overflow-tooltip />
        <px-table-column prop="revertStatus" label="归还状态" min-width="90" show-overflow-tooltip>
          <template #default="scope">
            <px-tag
              effect="plain"
              :style="{
                color: 'rgba(0, 0, 0, 0.8)',
                border: `1px solid ${scope.row.revertStatus === 1 ? '#4CCBA1' : '#F7B648'}`,
                backgroundColor: `${scope.row.revertStatus === 1 ? '#E8F8F3' : '#FEF5E6'}`
              }"
            >
              {{ scope.row.revertStatusDesc }}
            </px-tag>
          </template>
        </px-table-column>
        <px-table-column prop="classNameDesc" label="工具科室" min-width="90" show-overflow-tooltip />
        <!-- <px-table-column prop="toolCategoryDesc" label="工具分类" min-width="100" show-overflow-tooltip /> -->
        <!-- <px-table-column prop="toolModel" label="型号/规格" min-width="120" show-overflow-tooltip /> -->
        <!-- <px-table-column prop="brandVal" label="品牌" min-width="120" show-overflow-tooltip /> -->
        <!-- <px-table-column prop="custodianName" label="管理人" min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="updateName" label="操作人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="toolBorrowerName" label="借用人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="borrowClassNameDesc" label="借用人科室" min-width="120" show-overflow-tooltip />
        <px-table-column prop="toolBorrowDate" label="借用时间" min-width="140" show-overflow-tooltip />
        <px-table-column prop="toolBorrowUse" label="借出用途" min-width="140" show-overflow-tooltip />
        <px-table-column prop="toolReverterName" label="归还人" min-width="120" show-overflow-tooltip />
        <px-table-column prop="toolRevertDate" label="归还时间" min-width="140" show-overflow-tooltip />
        <px-table-column prop="remark" label="备注" min-width="100" show-overflow-tooltip />
        <px-table-column fixed="right" label="操作" width="80">
          <template #default="scope">
            <px-tooltip content="归还" placement="top">
              <px-button
                v-has="'ALL_EQUIP_TOOLMANAGE_LOANRETURN_RETURN'"
                :disabled="scope.row.revertStatus === 1"
                link
                type="danger"
                icon="logout"
                @click="handleReturn(scope.row)"
              />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddToolBorrowPage :isMain="isMain" :isView="isView" :toolBorrowId="toolBorrowId" @queryTable="queryTable" @backMainPage="backMainPage" />
    <!-- 详情查看页面 -->
    <ViewToolDetail :isMain="isMain" :isView="isView" :toolBorrowId="toolBorrowId" @backMainPage="backMainPage" />
    <!-- 归还弹窗 -->
    <RevertToolDialog
      :visible="dialogVisible"
      :isSimple="isSimple"
      :isShowDetail="isShowDetail"
      :rowData="rowData"
      :toolId="toolBorrowId"
      @closeDialog="closeDialog"
      @queryTable="queryTable"
    />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_TOOLMANAGE_LOANRETURN"
});
import { queryDictData } from "@/api/common";
import { queryToolLoanList } from "@/api/equip/toolManage";
import { isHasPermission } from "@/utils/auth";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { onActivated, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { reverseStatusList } from "../data";
import AddToolBorrowPage from "./components/AddToolBorrowPage.vue";
import RevertToolDialog from "./components/RevertToolDialog.vue";
import ViewToolDetail from "./components/ViewToolDetail.vue";

const route = useRoute();
const router = useRouter();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  queryParams: {
    toolClassName: "",
    revertStatus: "",
    pageNum: 1,
    pageSize: 20
  },
  custodianList: [],
  tableData: [],
  total: 0,
  selectIds: [],
  classNameList: [],
  facList: [],
  toolBorrowId: undefined,
  rowData: {},
  isShowDetail: false,
  dialogVisible: false,
  isSimple: false // 是否是批量归还
});
const {
  isMain,
  isView,
  custodianList,
  tableData,
  queryParams,
  total,
  selectIds,
  classNameList,
  facList,
  toolBorrowId,
  rowData,
  isShowDetail,
  dialogVisible,
  isSimple
} = toRefs(state);

// 进入页面时触发
onActivated(async () => {
  const { type, id, code } = route.query;
  if (type === "add") {
    toolBorrowId.value = +id;
    isMain.value = false;
    isView.value = false;
  } else if (type === "view") {
    toolBorrowId.value = +id;
    isMain.value = false;
    isView.value = true;
  } else if (type === "list") {
    queryParams.value.toolBorrowCode = code;
    isMain.value = true;
    isView.value = true;
    queryTable();
    classNameList.value = await queryDictData({ typeCode: "className" });
    facList.value = await queryDictData({ typeCode: "factoryArea" });
    custodianList.value = await getEmployeeIdAndName();
  } else {
    isMain.value = true;
    isView.value = true;
    queryTable();
    classNameList.value = await queryDictData({ typeCode: "className" });
    facList.value = await queryDictData({ typeCode: "factoryArea" });
    custodianList.value = await getEmployeeIdAndName();
  }
});

// 查询工具借用单列表
const queryTable = async () => {
  const data = await queryToolLoanList(queryParams.value);
  tableData.value = data?.data || [];
  total.value = data?.total || 0;
};
// 重置筛选条件和备件列表
const resetTable = async () => {
  queryParams.value = {
    toolNameOrCode: "",
    toolClassName: "",
    toolCode: "",
    revertStatus: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};

// 表格多选框选中
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
};
// 多选时该行是否可以选中
const handleCanSelect = row => {
  return row.revertStatus !== 1;
};
// 工具归还-批量
const batchReturn = async () => {
  isSimple.value = false;
  dialogVisible.value = true;
  toolBorrowId.value = selectIds.value;
};
// 工具归还-单个
const handleReturn = (row: any) => {
  isSimple.value = true;
  rowData.value = row;
  isShowDetail.value = true;
  dialogVisible.value = true;
  toolBorrowId.value = row.id;
};
// 查看工具借用单详情
const handleView = (row: any) => {
  toolBorrowId.value = row.id;
  isMain.value = false;
  isView.value = true;
};

// 查看工具台账详情
const handleViewTool = (row: any) => {
  const { toolId, status } = row;
  router.push(`/all/equip/toolManage/ledger?type=view&id=${toolId}`);
};
// 添加借用单详情
const addToolsBorrow = () => {
  isMain.value = false;
  isView.value = false;
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  toolBorrowId.value = "";
  if (route?.query && route?.query?.id) {
    router.push({ query: {} });
  }
};
// 关闭归还弹窗
const closeDialog = () => {
  toolBorrowId.value = "";
  isShowDetail.value = false;
  rowData.value = {};
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");
:deep(.px-table__cell) {
  padding: 0;
  height: 36px;
  line-height: 36px;
  .cell {
    height: 36px;
    line-height: 36px;
  }
}
</style>
